package com.nakamachizu.controller.mixi;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;
import org.slim3.util.TimeZoneLocator;

import com.google.appengine.api.datastore.KeyFactory;
import com.nakamachizu.collection.ApiKeyMap;
import com.nakamachizu.collection.IconNameMap;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.model.LandMarkData;
import com.nakamachizu.model.MapData;
import com.nakamachizu.model.MemberData;
import com.nakamachizu.model.session.MixiSessionData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.util.ErrorsUtil;

public class ViewController extends Controller {

    private String mixiSessionKey;
    
    private static final Logger log = Logger.getLogger(ViewController.class.getName());
    
    protected List<String> messages = new ArrayList<String>();
    private String zoomLevel;
    private String centerLat;
    private String centerLng;
    private Calendar now;
    
    @Override
    public Navigation run() throws Exception {

        MapDataService mds = new MapDataService();
        MapData map = null;
        
        if(validate()){
            mixiSessionKey = requestScope("sid");
            MixiSessionData session = mds.getMixiSessionData(mixiSessionKey);
            
            if(session.isOwner()){
                map = mds.getMapData(session.getAdminMailAddress());
            }
            
            requestScope("ownerId", session.getOwnerId());
        }
        
        if(map == null){
            return forward("/jsp/pc/mixi/error.jsp");
        }
        
        init();
        
        Integer w = 600;
        Integer h = 370;
        
        List<MemberData> memList = map.getMemberDataListRef().getModelList();
        List<LandMarkData> landList = map.getLandMarkDataListRef().getModelList();

        if(StringUtil.isEmpty(centerLat) || StringUtil.isEmpty(centerLng)){
            if(landList != null && landList.size() > 0){
                centerLat = Float.toString(landList.get(0).getLatLng().getLatitude());
                centerLng = Float.toString(landList.get(0).getLatLng().getLongitude());
            }else if(memList != null && memList.size() > 0){
                centerLat = Float.toString(memList.get(0).getLatLng().getLatitude());
                centerLng = Float.toString(memList.get(0).getLatLng().getLongitude());
            }else{
                centerLat = "35.6810976";
                centerLng = "139.7671169";
            }
        }
        requestScope("landMarkList", landList);
        requestScope("memberList", memList);
        
        requestScope("cLat", centerLat);
        requestScope("cLng", centerLng);
        requestScope("zoom", zoomLevel);
        requestScope("messages", messages);
        requestScope("now", now.getTime().getTime());
        requestScope("serverName", request.getServerName());
        requestScope("apiKey", ApiKeyMap.API_KEY_MAP.get(request.getServerName()));
        requestScope("width", w);
        requestScope("height", h);
        requestScope("iconNameMap", IconNameMap.ICON_NAME);
        requestScope("expire", map.getExpire());
        requestScope("mapKey", map.getAccessKey());
        requestScope("viewPassword", map.getViewPassword());
        requestScope("title", map.getTitle());
        //sessionScope(SessionKeyConstant.MAP_DATA_SESSION_KEY(), mds.createMapDataSession(map));
        
        return forward("/jsp/pc/mixi/view.jsp");

    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("sid", v.required());
        result = v.validate();
        
        return result;
    }
    
    protected void init(){
        now = Calendar.getInstance(TimeZoneLocator.get());
        zoomLevel = requestScope("zoom");
        if(StringUtil.isEmpty(zoomLevel)){
            zoomLevel = AppConstant.DEFAULT_ZOOM_LEVEL();
        }


    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("/jsp/pc/mixi/error.jsp");
    }
}
